﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace TaDMS.Models
{
    public class TaskEmployeeRepository : Repository<TaskEmployee>
    {
        public new string ErrorMessage { get; set; }

        public TaskEmployeeRepository(DbContext model)
            : base(model)
        {
        }

        public bool UpdateList(List<Employee> source, int taskId)
        {
            try
            {
                //var oldSource = model.TaskEmployees.Where(v => v.TaskId == taskId).OrderBy(v => v.EmployeeId).Select(v => v.EmployeeId).ToList();
                int? total;
                var oldSource = base.GetData(out total, orderBy: order => order.OrderBy(v => v.EmployeeId), filter: v => v.TaskId == taskId).Select(v => v.EmployeeId).ToList();
                var newSource = source.OrderBy(v => v.EmployeeId).Select(v => v.EmployeeId).ToList();
                if (!(oldSource.Count > 0))
                {
                    foreach (var i in newSource)
                    {
                        base.Create(new TaskEmployee() { TaskId = taskId, EmployeeId = i });
                    }
                }
                else
                {
                    foreach (var newItem in newSource)
                    {
                        if (oldSource.Contains(newItem))
                        {
                            oldSource.RemoveAll(v => v == newItem);
                        }
                        else
                        {
                            base.Create(new TaskEmployee() { TaskId = taskId, EmployeeId = newItem });
                        }
                    }

                    foreach (var i in oldSource)
                    {
                        base.Delete(v => v.TaskId == taskId && v.EmployeeId == i);
                    }
                }

                return true;
            }
            catch (Exception exception)
            {
                ErrorMessage = exception.Message;
                return false;
            }
        }
    }
}